#include <Arduino.h>

uint32_t pulseIn(uint32_t pin, uint32_t state, uint32_t timeout)
{
    uint32_t bit = digitalPinToBitMask(pin);
    __IO uint32_t *portIn = portInputRegister(digitalPinToPort(pin));

    uint32_t stateMask = (state ? bit : 0);
    uint32_t startMicros = micros();

    while ((*portIn & bit) == stateMask)
    {
        if (micros() - startMicros > timeout)
        {
            return 0;
        }
    }

    while ((*portIn & bit) != stateMask)
    {
        if (micros() - startMicros > timeout)
        {
            return 0;
        }
    }

    uint32_t start = micros();

    while ((*portIn & bit) == stateMask)
    {
        if (micros() - startMicros > timeout)
        {
            return 0;
        }
    }

    return (micros() - start);
}

uint32_t pulseInLong(uint32_t pin, uint32_t state, uint32_t timeout)
{
    return pulseIn(pin, state, timeout);
}
